#!/usr/bin/env sh

tmp_dir="/home/basil/mpi/tmp/kambiz"
input_dir=${tmp_dir}/Input
pre_node="Node"
pre_ele="Element"
pre_part="Part-me"

machinefile="/home/basil/mpi/hosts.mf"
bench_bin="/home/basil/mpi/bench_kambiz/bench3/benchMetis"

# Check input files existence
if [ $# -ne 3 ];
then 
    echo "Usage: $0 <Node file> <Element file> <Partition file>";
    exit
fi

if [ ! -r $1 ];
then
    echo "Node file $1 is not readable";
    exit
elif [ ! -r $2 ];
then
    echo "Element file $2 is not readable"
    exit
elif [ ! -r $3 ];
then
    echo "Partition file $3 is not readable"
    exit
fi

# Create temporary directory
if [ ! -d $input_dir ];
then
    mkdir -p $input_dir;
fi

# Determines number of nodes, elements and partitions:
nbnode=`head -1 $1 | gawk '{print $1}'`
nbele=`head -1 $2 | gawk '{print $1}'`
nbparts=`gawk 'BEGIN{max=0;} $1>max {max=$1;} END{print max+1}' $3`
#echo "nbnode = $nbnode"
#echo "nbelements = $nbele"
#echo "nbparts = $nbparts"
if [ $nbparts -gt 16 ];
then 
    echo "$nbparts is a big number of partitions!";
    exit;
fi

# Rename and move files

cp $1 ${input_dir}/${pre_node}$nbnode
cp $2 ${input_dir}/${pre_ele}$nbnode
cp $3 ${input_dir}/${pre_part}${nbnode}-${nbparts}

# Sleep to be sure that the directory have been created
#sleep 2;

#echo "mpiexec -machinefile $machinefile -n $nbparts -wdir ${tmp_dir} $bench_bin $nbnode $nbparts"  ;
mpiexec -machinefile $machinefile -n $nbparts -wdir ${tmp_dir} $bench_bin $nbnode $nbparts < /dev/null;

if [ -d $tmp_dir ];
then
    rm -Rf $tmp_dir;
fi

exit

   
